import czdbService from "../services/czdb.service.js";
import { validateIp, cleanIp, getRealClientIp } from "../utils/ip.validator.js";

const initializeDb = async (req, res, next) => {
  try {
    const { ipv4DbPath, ipv6DbPath, key } = req.body;

    if (!key) {
      return res.status(400).json({
        success: false,
        message: "缺少必要的密钥参数",
      });
    }

    if (!ipv4DbPath && !ipv6DbPath) {
      return res.status(400).json({
        success: false,
        message: "至少需要提供一个数据库文件路径",
      });
    }

    const initialized = czdbService.initialize(ipv4DbPath, ipv6DbPath, key);

    if (!initialized) {
      return res.status(500).json({
        success: false,
        message: "数据库初始化失败",
      });
    }

    res.json({
      success: true,
      message: "数据库初始化成功",
    });
  } catch (error) {
    console.error("初始化数据库失败:", error);
    next(error);
  }
};

const searchIp = async (req, res, next) => {
  try {
    const { ip } = req.params;

    if (!ip) {
      return res.status(400).json({
        success: false,
        message: "请提供IP地址",
      });
    }

    // 清理IP地址
    const cleanIpAddress = cleanIp(ip);
    
    if (!cleanIpAddress) {
      return res.status(400).json({
        success: false,
        message: "无法获取有效的IP地址",
      });
    }

    // 验证IP地址格式
    if (!validateIp(cleanIpAddress)) {
      console.warn(`无效的IP地址格式: ${cleanIpAddress}`);
      return res.status(400).json({
        success: false,
        message: `无效的IP地址格式: ${cleanIpAddress}`,
      });
    }

    if (!czdbService.isInitialized()) {
      return res.status(500).json({
        success: false,
        message: "数据库尚未初始化",
      });
    }

    const location = czdbService.searchIp(cleanIpAddress);

    if (!location) {
      return res.status(404).json({
        success: false,
        message: "未找到该IP的位置信息",
      });
    }

    res.json({
      success: true,
      data: {
        ip: cleanIpAddress,
        ...location,
      },
    });
  } catch (error) {
    console.error("IP查询失败:", error);
    next(error);
  }
};

const getClientIpInfo = async (req, res, next) => {
  try {
    // 使用新的真实IP获取函数
    let ip = getRealClientIp(req);

    // 检查是否是本地测试
    if (ip === "127.0.0.1" && (req.headers["cf-connecting-ip"] || req.headers["x-forwarded-for"])) {
      // 如果有代理头但IP是本地，可能是本地测试
      return res.json({
        success: true,
        data: {
          ip: "127.0.0.1",
          country: "本地",
          region: "本地",
          province: "本地",
          city: "本地",
          isp: "本地",
        },
      });
    }

    if (!ip) {
      return res.status(400).json({
        success: false,
        message: "无法获取客户端IP地址",
      });
    }

    // 验证IP地址格式
    if (!validateIp(ip)) {
      console.warn(`无效的IP地址格式: ${ip}`);
      return res.status(400).json({
        success: false,
        message: `无效的IP地址格式: ${ip}`,
      });
    }

    if (!czdbService.isInitialized()) {
      return res.status(500).json({
        success: false,
        message: "数据库尚未初始化",
      });
    }

    const location = czdbService.searchIp(ip);

    if (!location) {
      return res.status(404).json({
        success: false,
        message: "未找到该IP的位置信息",
      });
    }

    res.json({
      success: true,
      data: {
        ip,
        ...location,
      },
    });
  } catch (error) {
    console.error("IP查询失败:", error);
    next(error);
  }
};

const getIpFormatInfo = async (req, res, next) => {
  try {
    // 优先使用传入的IP参数
    let ip = req.params.ip;

    // 如果没有传入IP，则获取客户端真实IP地址
    if (!ip) {
      ip = getRealClientIp(req);
    }

    // 添加调试日志
    console.log("原始IP地址:", ip);
    console.log("请求头信息:", {
      "cf-connecting-ip": req.headers["cf-connecting-ip"],
      "x-forwarded-for": req.headers["x-forwarded-for"],
      "x-real-ip": req.headers["x-real-ip"],
      "x-forwarded-proto": req.headers["x-forwarded-proto"],
      "x-forwarded-host": req.headers["x-forwarded-host"],
    });

    // 检查是否是本地测试
    if (ip === "127.0.0.1" && !req.headers["cf-connecting-ip"] && !req.headers["x-forwarded-for"]) {
      return res.send("IP: 127.0.0.1 本地本地本地【本地】");
    }

    if (!ip) {
      return res.status(400).send("无法获取IP地址");
    }

    // 清理IP地址
    const originalIp = ip;
    ip = cleanIp(ip);
    console.log("清理后的IP地址:", ip);

    if (!ip) {
      return res.status(400).send("无法获取有效的IP地址");
    }

    // 验证IP地址格式
    if (!validateIp(ip)) {
      console.warn(`无效的IP地址格式: ${ip} (原始: ${originalIp})`);
      return res.status(400).send(`无效的IP地址格式: ${ip}`);
    }

    if (!czdbService.isInitialized()) {
      return res.status(500).send("数据库尚未初始化");
    }

    const location = czdbService.searchIp(ip);

    if (!location) {
      return res.status(404).send("未找到该IP的位置信息");
    }

    // 组合信息
    const parts = [];
    parts.push(`IP: ${ip} `);

    if (location.country) {
      parts.push(location.country);
    }
    if (location.province) {
      parts.push(location.province);
    }
    if (location.city) {
      parts.push(location.city);
    }
    if (location.isp) {
      parts.push(`【${location.isp}】`);
    }

    // 直接返回字符串
    res.send(parts.join(""));
  } catch (error) {
    console.error("IP查询失败:", error);
    next(error);
  }
};

export { initializeDb, searchIp, getClientIpInfo, getIpFormatInfo };
